Methods

Why Write Methods?

  1. Break a problem into small manageable pieces.
  2. Code reuse

void Methods and Value-Returning Methods

Two Parts of Method Declaration

Parts of a method header:

Calling a Method

Documenting Methods

Passing Arguments to a Method

Arguments: Values that are sent into a method.

Parameter: Variable that holds the value being passed into a method.

Arguments Passed by Value

Passed by Value: Only a copy of an argument’s value is passed into a parameter variable.

Passing Object References to a Method

When an object such as a String is passed as an argument, it is actually a reference to the object that is passed.

Strings are Immutable Objects

Immutable Objects: Objects that cannot be changed.

@param Tag and @return Tag in Documentation Comments

@param tag: Lets you provide a description of each parameter in your documentation comments.

@return tag: Lets you provide a description of the return value.

General Format:

@param parameterNameDescription

More About Local Variables

Local Variable: Variable declared inside a method.

Returning a Value from a Method

Data can be returned from a method to the statement that called it.

Example:

// Returns int value of 700 and assigned it to num
int num = Integer.parseInt("700");

return statement: Causes method to end execution, returning a value to the statement hat called the method.

Examples:

  1. Returning a boolean value
public static boolean isValid(int number)
{
    if (number > 100)
        return false;
    return true;
}
  1. Returning a Reference to a String Object
public static String fullname(String first, String last)
{
    return first + " " + last;
}